package com.yonyou.pmclouds.workstopreport.process;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yonyou.pmclouds.basecom.bp.processor.SingleProcessor;
import com.yonyou.pmclouds.basecom.entity.SuperVO;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.basecom.util.BeanHelper;
import com.yonyou.pmclouds.basecom.util.CommonFieldConst;
import com.yonyou.pmclouds.ncinvoker.entity.NCInvokerResult;
import com.yonyou.pmclouds.ncinvoker.entity.NCServiceVO;
import com.yonyou.pmclouds.ncinvoker.itf.NCInvoker;
import com.yonyou.pmclouds.project.entity.ProjectVO;
import com.yonyou.pmclouds.project.rmiitf.ProjectMaintain;
import com.yonyou.pmclouds.project.rmiitf.ProjectSimpleQuery;
import com.yonyou.pmclouds.workstopreport.entity.WorkStopVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * 停工单集成NCC接口
 *
 * @param <T>
 */
@Component
@Slf4j
public class WorkStopNCCProcessor<T extends SuperVO> implements SingleProcessor<T> {

    public static final String SERVICE_NAME = "StopWorkServlet";
    public static final String SERVICE_SERVLET_PATH = "/service/StopWorkServlet";
    public static final String NC_UBL_SERVICE = "nc.bs.pmcloud.servlet.ublimpl.StopWorkImp4UBL";

    @Autowired
    private NCInvoker invoker;
    @Autowired
    private ProjectSimpleQuery query;
    @Autowired
    private ProjectMaintain maintain;

    private ObjectMapper mapper = new ObjectMapper();

    public static final String UPDATE_SUCCESS_CODE = "update success";
    public static final String FLAG_CONST = "flag";
    public static final String PK_PROJECT_STATE_CONST = "pk_projectstate";

    public static final String BILL_TYPE_VALUE = "4D28";
    public static final String TRANSI_TYPE_VALUE = "4D28-01";

    @Override
    public void process(T vo, T orig) throws BusinessException {

        String pkProject = BeanHelper.getProperty(vo, CommonFieldConst.PK_PROJECT) == null ? (String)BeanHelper.getProperty(vo,CommonFieldConst.PKPROJECT) :
                (String)BeanHelper.getProperty(vo,CommonFieldConst.PK_PROJECT);

        if(StringUtils.isEmpty(pkProject))
            return;
        ProjectVO projectVO = query.queryProject(pkProject);
        if(projectVO == null || StringUtils.isEmpty(projectVO.getSrcType()) || StringUtils.isEmpty(projectVO.getPkSrc()))
            return;

        Map<String, Object> requestParams = getParam((WorkStopVO)vo,projectVO);


        NCServiceVO serviceVO = new NCServiceVO(SERVICE_NAME,SERVICE_SERVLET_PATH,NC_UBL_SERVICE);
        invoker.invokeAsync(serviceVO, requestParams, RuntimeEnvironment.getTenantId(),
                RuntimeEnvironment.getLoginUserId(), result -> {
                    if (NCInvokerResult.STATUS_OK.equals(result.getStatus())) {
                        if (result.getResult() == null) {
                            return;
                        }
                        try {
                            String callBackResult = result.getResult();
                            Map map = mapper.readValue(callBackResult, Map.class);

                            String jsonStr = map.get("result").toString();
                            if(null == jsonStr || "".equals(jsonStr)){
                                log.error("bill driven failed，info is {}", result);
                                return;
                            }
                            JSONObject jsonObject = JSON.parseObject(jsonStr);

                            if (!UPDATE_SUCCESS_CODE.equals(jsonObject.getString(FLAG_CONST))) {
                                log.error("bill driven failed，info is {}", result);
                                return;
                            }
                            maintain.updateForNCBillDriven(pkProject, jsonObject.getString(PK_PROJECT_STATE_CONST));
                        } catch (IOException e) {
                            log.error("unserialization failed, result is {}", result.getResult());
                        }
                    } else {
                        log.error("bill driven failed，info is {}", result);
                    }
                });
    }

    /**
     * 构建参数
     * TODO 增加所需的参数
     * @param vo
     * @return
     * @throws BusinessException
     */
    private Map<String, Object> getParam(WorkStopVO vo, ProjectVO projectVO) throws BusinessException {
        Map<String,Object> requestParams = new HashMap<>();
        requestParams.put("pkProject",projectVO.getPkSrc());
        requestParams.put("pkOrg",projectVO.getPkOrg());
        requestParams.put("billType",BILL_TYPE_VALUE);
        requestParams.put("transiType",TRANSI_TYPE_VALUE);
        requestParams.put("pkBill",vo.getPkWorkstopreport());
        requestParams.put("action","approved");
        requestParams.put("preRepeatDate",vo.getPreresumeDate());
        requestParams.put("stopDate",vo.getStopDate());
        return requestParams;
    }
}

